﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace Sio.Mdm.Security
{
    static class Config
    {
        static XML.config XmlConfig = null;
        static List<XML.configIgnoredNamesAdd> XmlIgnored;

        static Config()
        {
            LoadConfig();
        }

        public static bool IsIgnored(string token)
        {
            if (XmlConfig == null && !LoadConfig())
            {
                return false;
            }

            if (String.IsNullOrEmpty(token) && XmlConfig.Items[0].ignoreEmptyAndNull)
            {
                return true;
            }

            for (int i = 0; i < XmlIgnored.Count; i++)
            {
                bool result = false;

                switch (XmlIgnored[i].mask)
                {
                    case Sio.Mdm.Security.XML.MaskType.equals:
                        result = XmlIgnored[i].name == token;
                        break;
                    case Sio.Mdm.Security.XML.MaskType.contains:
                        result = token.Contains(XmlIgnored[i].name);
                        break;
                    case Sio.Mdm.Security.XML.MaskType.endsWith:
                        result = token.EndsWith(XmlIgnored[i].name);
                        break;
                    case Sio.Mdm.Security.XML.MaskType.startsWith:
                        result = token.StartsWith(XmlIgnored[i].name);
                        break;
                }

                if (result)
                {
                    return true;
                }
            }

            return false;
        }

        private static bool LoadConfig()
        {
            try
            {
                string path = String.Format("{0}\\TokenWriter.config", AppDomain.CurrentDomain.BaseDirectory);
                
                if(!File.Exists(path))
                {
                    return false;
                }

                StreamReader stream = new StreamReader(path);
                XmlSerializer serializer = new XmlSerializer(typeof(XML.config));

                XmlConfig = serializer.Deserialize(stream) as XML.config;
                XmlIgnored = new List<Sio.Mdm.Security.XML.configIgnoredNamesAdd>(XmlConfig.Items[0].add);
            }
            catch (Exception ex)
            {
#if DEBUG
                throw new Exception("'TokenWriter.config' has errors", ex);
#else
                return false;
#endif
            }

            return true;
        }
    }
}
